package com.nc.delivery_project.server.dao;

import com.nc.delivery_project.server.domain.Role;
import com.nc.delivery_project.server.domain.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by miroshnik on 01.12.14.
 */
public class UserDao extends AbstractDao<User> {
    
    protected final static String ENTITY_NAME = User.class.getSimpleName();
    
    protected final static String USER_ID = "USER_ID";
    protected final static String EMAIL = "EMAIL";
    protected final static String PASSWORD = "PASSWORD";
    protected final static String ROLE_ID = "ROLE_ID";

    public UserDao(String entityName) {
        super(entityName);
    }

    public UserDao(Connection connection, String entityName) throws SQLException {
        super(connection, entityName);
    }
    
    public UserDao(Connection connection) throws SQLException {
        this(connection, ENTITY_NAME);
    }

    public UserDao() {
        this(ENTITY_NAME);
    }

    @Override
    protected List<User> parseResultSet(ResultSet rs) throws SQLException {
        List<User> users = new ArrayList<>();

        while (rs.next()) {
            int userId = rs.getInt(USER_ID);
            String email = rs.getString(EMAIL);
            String pass = rs.getString(PASSWORD);
            int roleId = rs.getInt(ROLE_ID);

            Role role = new Role(roleId);

            users.add(new User(userId, email, pass, role));
        }

        return users;
    }

    @Override
    protected void prepareInsertStatement(CallableStatement statement, User object) throws SQLException {
        statement.setString(1, object.getEmail());
        statement.registerOutParameter(2, Types.NUMERIC);
        statement.setString(3, object.getEmail());
        statement.setString(4, object.getPassword());
        statement.setInt(5, object.getRole().getId());
    }

    @Override
    protected void prepareUpdateStatement(CallableStatement statement, User object) throws SQLException {
        statement.setInt(1, object.getId());
        statement.setString(2, object.getEmail());
        statement.setString(3, object.getEmail());
        statement.setString(4, object.getPassword());
        statement.setInt(5, object.getRole().getId());
    }
}
